package com.zem.imos.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zem.imos.Entity.*;
import com.zem.imos.Entity.Params.ParamsDoctor;
import com.zem.imos.Entity.Params.ParamsPatient;
import com.zem.imos.Mapper.DrugsMapper;
import com.zem.imos.Mapper.DrugsorderMapper;
import com.zem.imos.Mapper.RegisterMapper;
import com.zem.imos.Mapper.DoctorMapper;
import com.zem.imos.Util.JWT;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

@Service
public class DrugsService {
    @Autowired
    DrugsMapper drugsMapper;
    @Autowired
    DoctorMapper doctorMapper;
    @Autowired
    RegisterMapper registerMapper;
    @Autowired
    DrugsorderMapper drugsorderMapper;

    /**
     * 药品管理员增加新的药品
     * @author ZEM
     * @Time 2021/11/30
     * @Description 管理员增加新的药品
     */
    public RespEntity adddrugsbyadmin(HttpServletRequest request, Drug drugs)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            String username = claims.getId();
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", username);
            ParamsDoctor paramsDoctor = doctorMapper.selectOneDoctor(queryWrapper);

            if(paramsDoctor.getDepartmentName() != null && paramsDoctor.getDepartmentName().equals("药剂科"))
            {
                drugsMapper.insert(drugs);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"药品新增成功"));
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要药剂科医生。"));
            return res;

        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;

    }

    /**
     * 管理员删除药品
     * @author ZEM
     * @Time 2021/11/30
     * @Description 管理员增加新的药品
     */
    public RespEntity deletedrugsbyadmin(HttpServletRequest request, Long drugid)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            String username = claims.getId();
            QueryWrapper<User> queryWrapperYZ = new QueryWrapper();
            queryWrapperYZ.eq("username", username);
            ParamsDoctor paramsDoctor = doctorMapper.selectOneDoctor(queryWrapperYZ);

            if(paramsDoctor.getDepartmentName() != null && paramsDoctor.getDepartmentName().equals("药剂科"))
            {
                QueryWrapper<Drug> queryWrapper=new QueryWrapper();
                queryWrapper.eq("id", drugid);
                int isexist = drugsMapper.selectCount(queryWrapper);
                if(isexist == 1 )
                {
                    drugsMapper.deleteById(drugid);
                    RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"药品删除成功"));
                    return res;
                }
                else
                {
                    RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"该药品不存在！"));
                    return res;
                }

            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要药剂科医生。"));
            return res;

        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;

    }

    /**
     * 药品管理员更新药品
     * @author ZEM
     * @Time 2021/11/30
     * @Description 管理员更新药品
     * 测试
     */
    public RespEntity updatedrugsbyadmin(HttpServletRequest request, Drug drugs)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            String username = claims.getId();
            QueryWrapper<User> queryWrapperYZ = new QueryWrapper();
            queryWrapperYZ.eq("username", username);
            ParamsDoctor paramsDoctor = doctorMapper.selectOneDoctor(queryWrapperYZ);

            if(paramsDoctor.getDepartmentName() != null && paramsDoctor.getDepartmentName().equals("药剂科"))
            {
                QueryWrapper<Drug> queryWrapper=new QueryWrapper();
                queryWrapper.eq("id", drugs.getId());
                int isexist = drugsMapper.selectCount(queryWrapper);
                if(isexist == 1 )
                {
                    drugsMapper.updateById(drugs);
                    RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"药品信息更新成功"));
                    return res;
                }
                else
                {
                    RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"该药品不存在！"));
                    return res;
                }
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要药剂科医生。"));
            return res;

        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;

    }
    /**
     * 药品管理员查找药品
     * @author ZEM
     * @Time 2021/11/30
     * @Description 管理员按需查找药品
     */
    public RespEntity selectdrugsbyadmin(HttpServletRequest request, Page page,String  drug_name)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            String username = claims.getId();
            QueryWrapper<User> queryWrapperYZ = new QueryWrapper();
            queryWrapperYZ.eq("username", username);
            ParamsDoctor paramsDoctor = doctorMapper.selectOneDoctor(queryWrapperYZ);

            if(paramsDoctor.getDepartmentName() != null && paramsDoctor.getDepartmentName().equals("药剂科"))
            {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.like("drug_name", drug_name);
                IPage<List<Drug>> drugs = drugsMapper.selectPage(page,queryWrapper);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"药品查找成功"),drugs);
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要药剂科医生。"));
            return res;

        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;

    }

//    public RespEntity selectdrugsbyadmin(HttpServletRequest request, String name)
//    {
//        String token = request.getHeader("token");
//        Claims claims = JWT.parseJwt(token);
//        if(claims != null)
//        {
//            String id = claims.getId();
//            Doctor admin = workersMapper.selectById(id);
//            if(admin.getRole().equals("管理员") || admin.getRole().equals("药品管理员") )
//            {
//                QueryWrapper<Drug> queryWrapper=new QueryWrapper();
//                queryWrapper.like("name", name);
//                List<Drug> drugs = drugsMapper.selectList(queryWrapper);
//                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"药品查找成功"),drugs);
//                return res;
//            }
//            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要管理员。"));
//            return res;
//
//        }
//        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
//        return res;
//
//    }
//
//
    /**
     * 增减药品库存
     * @author ZSQ
     * @Time 2021/11/27
     * @Description 用药品id和增减数量来改变库存信息
     * 测试
     */
    // 药品库存增加或减少
    public RespEntity adddrugstockbyadmin(HttpServletRequest request, int drugsid, int num)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            String username = claims.getId();
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", username);
            ParamsDoctor paramsDoctor = doctorMapper.selectOneDoctor(queryWrapper);

            if(paramsDoctor.getDepartmentName() != null && paramsDoctor.getDepartmentName().equals("药剂科"))
            {
                Drug drug = drugsMapper.selectById(drugsid);
                if(drug!= null)
                {
                    drug.setDrugNum(num+drug.getDrugNum());
                    drugsMapper.updateById(drug);
                    RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"药品库存更新成功"));
                    return res;
                }
                else
                {
                    RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"药品库中没有该药品"));
                    return res;
                }


            }
            else
            {
                RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要药剂科医生。"));
                return res;
            }

        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;

    }

    /**
     * 获取用户挂号信息（患者id, 今天之内的）
     * @author ZSQ
     * @Time 2021/11/28
     * @Description 通过用户id获取24小时内完成就诊的挂号单 （就诊单）的开药信息和就诊信息
     * 测试
     */
    // 通过用户id获取24小时内完成就诊的挂号单 （就诊单）
    public RespEntity getregisterbyuserid(HttpServletRequest request , Page page, String patientId)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            String username = claims.getId();
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", username);
            ParamsDoctor paramsDoctor = doctorMapper.selectOneDoctor(queryWrapper);
            // 先验证token身份
            if(paramsDoctor.getDepartmentName() != null && paramsDoctor.getDepartmentName().equals("药剂科"))
            {
                // 拿到今天的日期进行筛选
                long nowTime =System.currentTimeMillis();
                long todayStartTime =nowTime - ((nowTime + TimeZone.getDefault().getRawOffset()) % (24 * 60 * 60 * 1000L));
                QueryWrapper<Register> queryWrapperPatient = new QueryWrapper();
                queryWrapperPatient.eq("patient_id", patientId);
                queryWrapperPatient.eq("date",todayStartTime);
                IPage<List<ParamsPatient>> registerList = registerMapper.selectRegisterDrugsOrder(page,queryWrapperPatient);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"成功"),registerList.getRecords());
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要药剂科医生。"));
            return res;
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;

    }

    /**
     * 获取用户挂号信息（挂号id）
     * @author ZSQ
     * @Time 2021/11/29
     * @Description 通过挂号单获取药品记录
     * 测试
     */
    // 通过挂号单获取药品记录
    public RespEntity getdrugsrecordbyregister(HttpServletRequest request , Page page, int registerId)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            String username = claims.getId();
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", username);
            ParamsDoctor paramsDoctor = doctorMapper.selectOneDoctor(queryWrapper);
            // 先验证token身份
            if(paramsDoctor.getDepartmentName() != null && paramsDoctor.getDepartmentName().equals("药剂科"))
            {
                QueryWrapper<Register> queryWrapperPatient = new QueryWrapper();
                queryWrapperPatient.eq("register.id", registerId);
                IPage<List<ParamsPatient>> registerList = registerMapper.selectRegisterDrugsOrder(page,queryWrapperPatient);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"成功"),registerList.getRecords());
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要药剂科医生。"));
            return res;
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;

    }

    /**
     * 获取用户药品记录
     * @author ZSQ
     * @Time 2021/11/29
     * @Description 通过用户id获取就诊的挂号单 （就诊单）的开药信息和就诊信息
     * 未测试
     */
    // 获取所有给药记录
    public RespEntity getalldrugsrecords(HttpServletRequest request, Page page, String patientId)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            String username = claims.getId();
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", username);
            ParamsDoctor paramsDoctor = doctorMapper.selectOneDoctor(queryWrapper);
            // 先验证token身份
            if(paramsDoctor.getDepartmentName() != null && paramsDoctor.getDepartmentName().equals("药剂科"))
            {
                QueryWrapper<Register> queryWrapperPatient = new QueryWrapper();
                queryWrapperPatient.eq("patient_id", patientId);
                IPage<List<ParamsPatient>> registerList = registerMapper.selectRegisterDrugsOrder(page,queryWrapperPatient);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"成功"),registerList.getRecords());
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"身份验证错误，需要药剂科医生。"));
            return res;
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;
    }




}
